package com.example.makerspace.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.makerspace.model.ERNIEBotReqBody;
import com.example.makerspace.model.Message;
import com.google.common.collect.Lists;
import okhttp3.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Objects;

public class BaiduUtils {
    public static final String API_KEY = "sNfOTzchKC79BrWKR6zrSoLQ";
    public static final String SECRET_KEY = "6VoFj27L6CSiZiEmHrZQffxyZdbUpaXK";
    public static final String URL = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static void main(String []args) throws IOException {
        long statr = System.currentTimeMillis();
        InputStream is = null;
        String urlStr = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=" + getAccessToken();
        //11.读取输入流中的返回值
        StringBuffer bu = new StringBuffer();
        try {
            //1.设置URL
            URL url = new URL(urlStr);
            //2.打开URL连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //3.设置请求方式
            conn.setRequestMethod("POST");
            //4.设置Content-Type
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            //5.设置Accept
            conn.setRequestProperty("Accept", "text/event-stream");
            //6.设置DoOutput
            conn.setDoOutput(true);
            //7.设置DoInput
            conn.setDoInput(true);
            //8.获取输出流
            OutputStream os = conn.getOutputStream();
            //9.写入参数（json格式）
            List<Message> messages = Lists.newArrayList(
                new Message("user", "我叫李瑞凡"),
                new Message("assistant", "很高兴认识您，李瑞凡。请问您有什么需要我帮助的吗？"),
                new Message("user", "帮我写一篇100字的作文")
                );
            ERNIEBotReqBody ernieBotReqBody = new ERNIEBotReqBody();
            ernieBotReqBody.setMessages(messages);
            ernieBotReqBody.setStream(Boolean.TRUE);
            String json = JSON.toJSONString(ernieBotReqBody);
            os.write(json.getBytes("utf-8"));
            os.flush();
            os.close();
            //10.获取输入流
            is = conn.getInputStream();

            byte[] bytes = new byte[1024];
            int len = 0;
            long end = System.currentTimeMillis();
            List<JSONObject> jsonObjects = Lists.newArrayList();
            while ((len = is.read(bytes)) != -1) {
                String line = new String(bytes, 0, len, "utf-8");
                System.out.println(line);
                System.out.println();
                bu.append(line);
            }
            String res = bu.toString();
            StringBuilder sb = new StringBuilder();
            String substring;
            while(StringUtils.isNotBlank(res)){
                res = res.replaceFirst("data: ", "");
                int index = res.indexOf("data: ");
                if(index != -1){
                    substring = res.substring(0, index);
                }else{
                    substring = res;
                }
                JSONObject jsonObject = JSON.parseObject(substring, JSONObject.class);
                sb.append(jsonObject.getString("result"));
                res = res.substring(substring.length());
            }
//            System.out.println(sb);
        } catch (IOException e) {
        } finally {
            if (!Objects.isNull(is)) {
                try {
                    //12.关闭输入流
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    public static String postEventStream(String json, HttpServletResponse response) {
        InputStream is = null;
        //11.读取输入流中的返回值
        StringBuffer bu = new StringBuffer();
        StringBuilder sb = new StringBuilder();
        response.setContentType("text/plain;charset=utf-8");
        try {
            //1.设置URL
            URL url = new URL(URL + getAccessToken());
            //2.打开URL连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //3.设置请求方式
            conn.setRequestMethod("POST");
            //4.设置Content-Type
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            //5.设置Accept
            conn.setRequestProperty("Accept", "text/event-stream");
            //6.设置DoOutput
            conn.setDoOutput(true);
            //7.设置DoInput
            conn.setDoInput(true);
            //8.获取输出流
            OutputStream os = conn.getOutputStream();
            //9.写入参数（json格式）
            os.write(json.getBytes("utf-8"));
            os.flush();
            os.close();
            //10.获取输入流
            is = conn.getInputStream();

            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                String line = new String(bytes, 0, len, "utf-8");

                response.getWriter().write(line);
                response.getWriter().flush();
//                response.getOutputStream().write(bytes);
//                response.getOutputStream().flush();
                bu.append(line);
            }
            String res = bu.toString();
            String substring;
            while(StringUtils.isNotBlank(res)){
                res = res.replaceFirst("data: ", "");
                int index = res.indexOf("data: ");
                if(index != -1){
                    substring = res.substring(0, index);
                }else{
                    substring = res;
                }
                JSONObject jsonObject = JSON.parseObject(substring, JSONObject.class);
                sb.append(jsonObject.getString("result"));
                res = res.substring(substring.length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (!Objects.isNull(is)) {
                try {
                    //12.关闭输入流
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return sb.toString();
    }



    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        JSONObject jsonObject = JSON.parseObject(response.body().string(), JSONObject.class);
        return jsonObject.getString("access_token");
    }

}
